<template>
  <div class="add-goods">
    <el-dialog
      class="dialog"
      title="新增商品"
      width="750px"
      top="8vh"
      :visible.sync="dialog"
      :modal-append-to-body="false"
    >
      <div class="form-wrapper">
        <div class="form-flex">
          <div class="form-item">
            <el-alert
              title="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，XXX有依据国家规定及平台规则进行处理的权利"
              type="warning"
              show-icon
              :closable="false"
            ></el-alert>
            <el-form :model="form" :rules="rules" ref="form" label-width="110px">
              <el-collapse v-model="activeNames" accordion>
                <el-collapse-item title="基本信息" name="1">
                  <el-form-item label="课程名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入课程名称，最多15个汉字"></el-input>
                  </el-form-item>
                  <el-form-item label="课程描述" prop="description">
                    <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述"></el-input>
                  </el-form-item>
                  <el-form-item label="图文详情" prop="productURL">
                    <div class="editor">
                      <quill-editor v-model="form.productURL" :options="editorOption"></quill-editor>
                    </div>
                  </el-form-item>
                  <el-form-item label="机构名称" prop="madeBy">
                    <el-input v-model="form.madeBy" placeholder="请输入合作机构名称"></el-input>
                  </el-form-item>
                  <el-form-item label="标签" prop="tags">
                    <el-select
                      v-model="form.tags"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="输入后按回车键添加标签，可添加多组"
                    ></el-select>
                  </el-form-item>
                  <div class="flex-part part-width2">
                    <div class="part-item">
                      <el-form-item label="商品分组" prop="classID">
                        <el-select v-model="form.classID" placeholder="请选择商品分组">
                           <!-- <el-option label="分组一" value="分组一"></el-option>
                          <el-option label="分组二" value="分组二"></el-option> -->
                           <el-option v-for="item in productClassList"
                            :label="item.className"
                            :key="item.classID"
                            :value="item.classID"
                           >
                          </el-option>
                        </el-select>
                        
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="售卖类型" prop="saleType">
                        <el-radio-group v-model="form.saleType">
                          <el-radio :label="0">正品</el-radio>
                          <el-radio :label="1">试用</el-radio>
                          <el-radio :label="2">拓客</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </div>
                  </div>
                  <el-form-item label="购买结果链接" prop="resultURL">
                    <div class="editor">
                      <quill-editor v-model="form.resultURL" :options="editorOption"></quill-editor>
                    </div>
                  </el-form-item>
                </el-collapse-item>
                <el-collapse-item title="商品图片" name="2">
                  <div class="flex-part">
                    <div class="part-item">
                      <el-form-item label="商品小图片" prop="smallPicture">
                        <el-upload
                          class="uploader"
                          action
                          :show-file-list="false"
                          :auto-upload="false"
                          :on-change="chooseImg"
                          accept="image/jpeg, image/png"
                        >
                          <img
                            v-if="form.smallPicture"
                            @click="currentImg('smallPicture')"
                            :src="form.smallPicture"
                            class="uploader-preview"
                          >
                          <i
                            v-else
                            @click="currentImg('smallPicture')"
                            class="el-icon-plus uploader-icon"
                          ></i>
                        </el-upload>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="商品大图片" prop="bigPicture">
                        <el-upload
                          class="uploader"
                          action
                          :show-file-list="false"
                          :auto-upload="false"
                          :on-change="chooseImg"
                          accept="image/jpeg, image/png"
                        >
                          <img
                            v-if="form.bigPicture"
                            @click="currentImg('bigPicture')"
                            :src="form.bigPicture"
                            class="uploader-preview"
                          >
                          <i
                            v-else
                            @click="currentImg('bigPicture')"
                            class="el-icon-plus uploader-icon"
                          ></i>
                        </el-upload>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="商品海报" prop="poster">
                        <el-upload
                          class="uploader"
                          action
                          :show-file-list="false"
                          :auto-upload="false"
                          :on-change="chooseImg"
                          accept="image/jpeg, image/png"
                        >
                          <img
                            v-if="form.poster"
                            @click="currentImg('poster')"
                            :src="form.poster"
                            class="uploader-preview"
                          >
                          <i
                            v-else
                            @click="currentImg('poster')"
                            class="el-icon-plus uploader-icon"
                          ></i>
                        </el-upload>
                      </el-form-item>
                    </div>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="开关设置" name="3">
                  <div class="flex-part">
                    <div class="part-item">
                      <el-form-item label="置于Banner" prop="onBanner">
                        <el-switch v-model="form.onBanner" :active-value="0" :inactive-value="1"></el-switch>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="置于首页" prop="onHomepage">
                        <el-switch v-model="form.onHomepage" :active-value="0" :inactive-value="1"></el-switch>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="是否上架" prop="status">
                        <el-switch v-model="form.status" :active-value="0" :inactive-value="1"></el-switch>
                      </el-form-item>
                    </div>
                  </div>
                  <div class="flex-part">
                    <div class="part-item">
                      <el-form-item label="是否团购" prop="isGroupBuy">
                        <el-switch v-model="form.isGroupBuy" :active-value="0" :inactive-value="1"></el-switch>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="是否邮寄" prop="isPost">
                        <el-switch v-model="form.isPost" :active-value="0" :inactive-value="1"></el-switch>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="线下发放绩效" prop="isIssueOffline">
                        <el-switch
                          v-model="form.isIssueOffline"
                          :active-value="0"
                          :inactive-value="1"
                        ></el-switch>
                      </el-form-item>
                    </div>
                    <el-form-item label="不允许推广" prop="isDistribution">
                    <el-switch v-model="form.isDistribution" :active-value="1" :inactive-value="0"></el-switch>
                  </el-form-item>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="团购信息" name="4">
                  <div class="flex-part part-width2">
                    <div class="part-item">
                      <el-form-item label="团购人数" prop="numberOfMember">
                        <el-input type="number" v-model.number="form.numberOfMember">
                          <template slot="append">人</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="团购时效" prop="duration">
                        <el-input type="number" v-model.number="form.duration">
                          <template slot="append">小时</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-collapse-item>
                <el-collapse-item
                  v-for="(priceList, index) in form.priceList"
                  :key="priceList.id"
                  :name="String(index + 7)"
                >
                  <template slot="title">
                    <div class="flex-row" style="padding-right: 20px;">
                      <div>价格策略（{{index + 1}}）</div>
                      <div>
                        <el-button
                          v-if="index===0"
                          type="success"
                          size="small"
                          icon="el-icon-circle-plus"
                          @click="addPriceItem"
                          @click.stop
                        >增加一组</el-button>
                        <el-button
                          v-else
                          type="danger"
                          size="small"
                          icon="el-icon-remove"
                          @click="delPriceItem(index)"
                          @click.stop
                        >删除本组</el-button>
                      </div>
                    </div>
                  </template>
                  <div
                    class="flex-part part-width2"
                    v-for="(specList, specIndex) in priceList.specList"
                    :key="specList.id"
                  >
                    <div class="part-item">
                      <el-form-item
                        label="规格名"
                        :prop="'priceList.' + index + '.specList.' + specIndex + '.key'"
                        :rules="{
                          required: true, message: '规格名不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input v-model="specList.key" placeholder="如：颜色"></el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item
                        label="规格值"
                        :prop="'priceList.' + index + '.specList.' + specIndex + '.value'"
                        :rules="{
                          required: true, message: '规格值不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input v-model="specList.value" placeholder="如：白"></el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item2">
                      <el-form label-width="0px">
                        <el-form-item>
                          <el-button
                            v-if="specIndex===0"
                            type="primary"
                            size="small"
                            icon="el-icon-circle-plus"
                            @click="addSpec(priceList.specList)"
                            plain
                          >增加</el-button>
                          <el-button
                            v-else
                            type="primary"
                            size="small"
                            icon="el-icon-remove"
                            @click="delSpec(priceList.specList, specIndex)"
                            plain
                          >删除</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                  <div
                    class="flex-part part-width2"
                    v-for="(personalList, presonalIndex) in priceList.personalList"
                    :key="personalList.id"
                  >
                    <div class="part-item">
                      <el-form-item label="推广员手机号" prop="distributorIDList">
                        <el-select
                          v-model="personalList.distributorIDList"
                          multiple
                          filterable
                          allow-create
                          default-first-option
                          placeholder="输入后按回车键添加推广员，可添加多组"
                        ></el-select>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item label="推广员绩效" prop>
                        <el-input type="number" v-model.number="personalList.income" placeholder>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item2">
                      <el-form label-width="0px">
                        <el-form-item>
                          <el-button
                            v-if="presonalIndex===0"
                            type="primary"
                            size="small"
                            icon="el-icon-circle-plus"
                            @click="addSpec(priceList.personalList)"
                            plain
                          >增加</el-button>
                          <el-button
                            v-else
                            type="primary"
                            size="small"
                            icon="el-icon-remove"
                            @click="delSpec(priceList.personalList, presonalIndex)"
                            plain
                          >删除</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                  <div
                    class="flex-part part-width2"
                    v-for="(incomeClassList, incomeIndex) in priceList.incomeClassList"
                    :key="incomeClassList.id"
                  >
                    <div class="part-item">
                      <el-form-item
                        label="级别选择"
                        :prop="'priceList.' + index + '.incomeClassList.' + incomeIndex + '.classID'"
                        :rules="{
                          required: true, message: '请选择级别', trigger: 'change'
                        }"
                      >
                        <el-select v-model="incomeClassList.classID" placeholder="请选级别名称">
                          <el-option label="分组一" value="分组一"></el-option>
                          <el-option label="分组二" value="分组二"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item
                        label="级别绩效"
                        :prop="'priceList.' + index + '.incomeClassList.' + incomeIndex + '.income'"
                        :rules="{
                          required: true, message: '级别绩效不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input type="number" v-model.number="incomeClassList.income" placeholder>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item2">
                      <el-form label-width="0px">
                        <el-form-item>
                          <el-button
                            v-if="incomeIndex===0"
                            type="primary"
                            size="small"
                            icon="el-icon-circle-plus"
                            @click="addIncome(priceList.incomeClassList)"
                            plain
                          >增加</el-button>
                          <el-button
                            v-else
                            type="primary"
                            size="small"
                            icon="el-icon-remove"
                            @click="delSpec(priceList.incomeClassList, incomeIndex)"
                            plain
                          >删除</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                  <div class="flex-part part-width2">
                    <div class="part-item">
                      <el-form-item
                        label="商品原价"
                        :prop="'priceList.' + index + '.originalPrice'"
                        :rules="{
                          required: true, message: '商品原价不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input
                          type="number"
                          v-model.number="priceList.originalPrice"
                          placeholder="请输入商品原价"
                        >
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item
                        label="立即购买价"
                        :prop="'priceList.' + index + '.instantPrice'"
                        :rules="{
                          required: true, message: '立即购买价不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input
                          type="number"
                          v-model.number="priceList.instantPrice"
                          placeholder="请输入立即购买价"
                        >
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </div>
                  <div class="flex-part part-width2">
                    <div class="part-item">
                      <el-form-item
                        label="团购价"
                        :prop="'priceList.' + index + '.groupPrice'"
                        :rules="{
                          required: true, message: '团购价不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input type="number" v-model.number="priceList.groupPrice" placeholder>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="part-item">
                      <el-form-item
                        label="团长价"
                        :prop="'priceList.' + index + '.leaderPrice'"
                        :rules="{
                          required: true, message: '团长价不能为空', trigger: 'blur'
                        }"
                      >
                        <el-input type="number" v-model.number="priceList.leaderPrice" placeholder>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </div>
                  <el-form-item label="允许购买多个" prop="isMultiple">
                    <el-switch v-model="priceList.isMultiple" :active-value="0" :inactive-value="1"></el-switch>
                  </el-form-item>
                  
                </el-collapse-item>
                <el-collapse-item title="线上佣金结算" name="5">
                  <el-form-item>
                    <el-radio v-model="incomeRadio" :label="0">即时发放</el-radio>
                  </el-form-item>
                  <el-form-item>
                    <div class="flex-row">
                      <el-radio v-model="incomeRadio" :label="1">定时发放</el-radio>
                      <el-date-picker
                        v-model="form.issueTime"
                        type="datetime"
                        :disabled="incomeRadio!==1"
                        placeholder="选择最迟退款时刻"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      ></el-date-picker>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <div class="flex-row">
                      <el-radio v-model="incomeRadio" :label="2">预时发放</el-radio>
                      <el-input
                        type="number"
                        :disabled="incomeRadio!==2"
                        v-model.number="form.issueDays"
                        placeholder="请输入逾期天数"
                      >
                        <template slot="append">天</template>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-collapse-item>
                <el-collapse-item title="退费设置" name="6">
                  <el-form-item>
                    <div class="flex-row">
                      <el-radio v-model="refundRadio" :label="0">不允许退费</el-radio>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <div class="flex-row">
                      <el-radio v-model="refundRadio" :label="1">截止至时间前可退费</el-radio>
                      <el-date-picker
                        v-model="form.latestRefundTime"
                        :disabled="refundRadio!==1"
                        type="datetime"
                        placeholder="选择时刻"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      ></el-date-picker>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <div class="flex-row">
                      <el-radio v-model="refundRadio" :label="2">购买后几天内可退费</el-radio>
                      <el-input
                        type="number"
                        :disabled="refundRadio!==2"
                        v-model.number="form.refundDays"
                      >
                        <template slot="append">天</template>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
              <el-form-item class="form-btns">
                <el-button type="primary" @click="submitForm">{{update?'确定修改':'立即创建'}}</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import { produceJsonFormat, produceJsonRules } from '@/api/produceJsonFormat'
import { productTypeListFast } from '@/api'

export default {
  name: 'add-goods',
  props: {
    form: Object,
    update: false
  },
  data() {
    return {
      radio: 1,
      productClassList:[],
      issueRadio: '',
      incomeRadio: 0,
      refundRadio: 0,
      editorOption: {
        placeholder: '可以直接粘贴其他编辑器中复制的内容',
        theme: 'bubble'
      },
      activeNames: ['1'],
      currentParam: '',
      dialog: false,
      personalList: {
        distributor: '',
        income: ''
      },
      incomeClassList: {
        classID: '',
        income: ''
      },
      rules: produceJsonRules
    }
  },
  created() {
    this.getProductClassList()
  },
  methods: {
    getProductClassList() {
      console.log(111)
      productTypeListFast().then((res) => {
        console.log(res)
        this.productClassList = res
      }).catch(err => {
        console.log(err)
        console.log(err.response.data)
      })
    },
 
    delSpec(currentList, index) {
      currentList.splice(index, 1)
    },
    addSpec(currentList) {
      currentList.push({
        key: '',
        value: ''
      })
    },
    addIncome(currentList) {
      currentList.push({
        classID: '',
        income: ''
      })
    },
    delPriceItem(index) {
      this.form.priceList.splice(index, 1)
    },
    addPriceItem() {
      let objectStr = JSON.stringify(produceJsonFormat.priceList)
      this.form.priceList.push(Object.assign({}, JSON.parse(objectStr)))
    },
    show() {
      this.dialog = true
    },
    hide() {
      this.dialog = false
    },
    submitForm() {
      if (!this.checkAgain()) {
        return false
      }
      this.$refs.form.validate((valid) => {
        console.log(this.form)
        if (valid) {
          this.$emit('addProduct', this.form)
        } else {
          this.$message.error('校验未通过，请补充完整')
          return false
        }
      })
    },
    checkAgain() {
      let priceList = this.form.priceList
      let flag = true
      priceList.forEach((item) => {
        item.personalList.forEach((person, index) => {
          if (index !== 0 && person.distributorIDList.length === 0 && !person.income) {
            this.$message.error('请删除多余推广员和推广员绩效组')
            flag = false
          }
          if (person.distributorIDList.length && !person.income || !person.distributorIDList.length && person.income) {
            this.$message.error('请确保推广员和推广员绩效成对出现')
            flag = false
          }
        })
      })
      return flag
    },
    resetForm() {
      this.form = produceJsonFormat
      this.$refs.form.resetFields()
    },
    currentImg(name) {
      this.currentParam = name
    },
    chooseImg(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      // const blob = URL.createObjectURL(file.raw)
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        // console.log(reader.result)
        this.form[this.currentParam] = reader.result
      }
    }
  },
  watch: {
    refundRadio(newVal, oldVal) {
      if (newVal === 0) {
        this.form.canRefund = 1
        this.form.latestRefundTime = null
        this.form.refundDays = null
      } else if (newVal === 1) {
        this.form.canRefund = 0
        this.form.refundDays = null
      } else {
        this.form.canRefund = 0
        this.form.latestRefundTime = null
      }
    },
    incomeRadio(newVal, oldVal) {
      if (newVal === 0) {
        this.form.issueImme = 0
        this.form.issueTime = null
        this.form.issueDays = null
      } else if (newVal === 1) {
        this.form.issueImme = 1
        this.form.issueDays = null
      } else {
        this.form.issueImme = 1
        this.form.issueTime = null
      }
    },
    form(val) {
      if (val.issueImme === 1) {
        if (val.issueDays) {
          this.incomeRadio = 2
        } else {
          this.incomeRadio = 3
        }
      } else {
        this.incomeRadio = 1
      }
      console.log(val.className)
      console.log(val.canRefund)
      console.log(val.refundDays)
      console.log(val.latestRefundTime)
      if (val.canRefund === 0) {
        if (val.refundDays) {
          this.refundRadio = 2
        } else {
          this.refundRadio = 3
        }
      } else {
        this.refundRadio = 1
      }
    }
  }
}
</script>

<style>
.uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.uploader .el-upload:hover {
  border-color: #409eff;
}
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.uploader-preview {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style scoped lang="stylus" rel="stylesheet/stylus">
@import '../style/mixin.styl'
.dialog
  & >>> .el-dialog__body
    padding 0
  & >>> .el-dialog__header
    background #f8f8f8
.form-wrapper
  max-height 74vh
  padding 20px 30px 0 30px
  overflow-y auto
  & >>> .el-collapse-item__content
    padding-top 25px
  .el-picker,.el-select,.el-input
    width 100%
  .flex-part
    flex-row()
  .form-btns
    margin-top 20px
  .part-width2
    .part-item
      flex 1
      width 330px
  .part-item2
    margin-left 30px
  .editor
    border 1px solid #dddddd
    border-radius 4px
    min-height 80px
    max-height 200px
    overflow auto
</style>
